package rpc.http.server;

import rpc.common.MyInvocation;
import rpc.register.MyLocalRegister;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;

/**
 * 自定义HttpServlet处理器
 */
public class MyHttpServletHandler {
    /**
     * 处理
     */
    public static void handle(HttpServletRequest reg, HttpServletResponse resp) {
        try {
            //从客户端请求获取输入流
            InputStream inputStream = reg.getInputStream();
            //构建对象输入流
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            //从对象输入流获取对象
            MyInvocation myInvocation = (MyInvocation) objectInputStream.readObject();
            //获取接口名称
            String interfaceName = myInvocation.getInterfaceName();
            //关闭对象输入流
            objectInputStream.close();
            //关闭输入流
            inputStream.close();

            //从本地注册获取接口实现类
            Class<?> classImpl = MyLocalRegister.get(interfaceName);
            //从实现类获取方法
            Method method = classImpl.getMethod(myInvocation.getMethodName(), myInvocation.getParameterTypes());
            //获取实现类对象
            Object object = classImpl.getDeclaredConstructor().newInstance();
            //执行方法获取返回参数
            String result = (String) method.invoke(object, myInvocation.getParameters());

            //从客户端返回获取输出流
            OutputStream outputStream = resp.getOutputStream();
            //写入返回参数
            outputStream.write(result.getBytes());
            //关闭输出流
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
